#pragma once
#include <sys/types.h>
#include <sys/socket.h>

#include <iostream>
using namespace std;

#include "Log.hpp"
#include "Common.hpp"
#include "InetAddr.hpp"
using namespace MyLogModule;

const int gdefault_listenSocket = -1;
const int gbacklog = 4;

namespace MySocketModule
{
    class Socket;
    using SockPtr = shared_ptr<Socket>;
    // 基类，规定Socket的方法
    class Socket
    {
    public:
        virtual ~Socket() = default;
        virtual void SocketOrDie() = 0;
        virtual bool BindOrDie(int port) = 0;
        virtual bool ListenOrDie() = 0;
        virtual SockPtr AcceptOrDie(InetAddr *client) = 0;
        virtual void Close() = 0;

        virtual int Recv(string *in) = 0;
        virtual int Send(string &out) = 0;
        virtual int GetSockfd() = 0;

        // 模板方法模式

        // 提供一个创建TcpSocket的固定套路
        void BuildTcpSocketMethod(int port)
        {
            SocketOrDie();
            BindOrDie(port);
            ListenOrDie();
        }

        // 提供一个创建UdpSocket的固定套路
        // void BuildUdpSocket(int port)
        // {
        //     SocketOrDie();
        //     BindOrDie(port);
        // }
    };

    // tcpSocket 具体实现基类Socket规定的方法
    class TcpSocket : public Socket
    {
    public:
        TcpSocket()
            : _listenSocket(gdefault_listenSocket)
        {
        }

        TcpSocket(int sockfd)
            : _listenSocket(sockfd) //使用已有的fd创建socket对象
        {
        }

        virtual ~TcpSocket()
        {
        }

        virtual void SocketOrDie() override
        {
            _listenSocket = ::socket(AF_INET, SOCK_STREAM, 0);
            if (_listenSocket < 0)
            {
                LOG(LogGrade::FATAL) << "socket create fail";
                Die(SOCKET_ERR);
            }
            LOG(LogGrade::NORMAL) << "socket create success,socket:" << _listenSocket;
        }

        virtual bool BindOrDie(int port) override
        {
            if (_listenSocket == gdefault_listenSocket)
                return false;
            InetAddr addr(port);
            int n = ::bind(_listenSocket, addr.Getaddr(), addr.Getlen());
            if (n < 0)
            {
                LOG(LogGrade::FATAL) << "bind fail";
                Die(BIND_ERR);
            }
            LOG(LogGrade::NORMAL) << "bind success,socket:" << _listenSocket;
            return true;
        }

        virtual bool ListenOrDie() override
        {
            if (_listenSocket == gdefault_listenSocket)
                return false;
            int n = ::listen(_listenSocket, gbacklog);
            if (n < 0)
            {
                LOG(LogGrade::FATAL) << "listen fail";
                Die(LISTEN_ERR);
            }
            LOG(LogGrade::NORMAL) << "listen success,socket:" << _listenSocket;
            return true;
        }

        // 返回值的目的：给调用方也返回一个socket
        virtual SockPtr AcceptOrDie(InetAddr *client) override
        {
            // accept后，要获得两样东西
            // 1. 文件描述符 fd
            // 2. 客户端信息
            if (nullptr == client)
                return nullptr;
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int fd = accept(_listenSocket, CONVERSE(&peer), &len);
            if (fd < 0)
            {
                LOG(LogGrade::FATAL) << "accept fail";
                return nullptr;
            }
            client->SetAddr(peer, len); // 获取客户端的信息

            return make_shared<TcpSocket>(fd); // 给调用方也返回一个socket，全部都以socket看待
        }

        virtual void Close() override
        {
            if (_listenSocket != gdefault_listenSocket)
                ::close(_listenSocket);
        }

        virtual int Recv(string *out) override
        {
            char buffer[1024];
            int size = ::recv(_listenSocket, buffer, sizeof(buffer)-1, 0);
            if (size > 0)
            {
                buffer[size] = 0;
                *out = buffer;
            }
            return size;
        }
        virtual int Send(string &out)
        {
            int size = ::send(_listenSocket, out.c_str(), out.size(), 0);
            return size;
        }

        virtual int GetSockfd() override
        {
            return _listenSocket;
        }

    private:
        int _listenSocket;
    };
}
